//
//  STCaptureImageViewController.m
//  STBest
//
//  Created by apple on 2017/9/1.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "STCaptureImageViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "STSportingManager.h"

@interface STCaptureImageViewController ()

@property (weak, nonatomic) IBOutlet UIView *previewView;

//会话
@property(strong, nonatomic) AVCaptureSession   *session;

//创建输入
@property(strong, nonatomic) AVCaptureInput     *videoInput;

//创建输出
@property(strong, nonatomic) AVCaptureStillImageOutput  *output;

// 是否是前置摄像头
@property (assign, nonatomic)   BOOL                  isFront;

@property (weak, nonatomic) IBOutlet UIImageView *waterprintImageView;

@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *leftFlashViewTrailingConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *rightFlashViewLeadingConstraint;
@property (weak, nonatomic) IBOutlet UIButton *captureButton;
@property (weak, nonatomic) IBOutlet UIButton *switchButton;

@end

@implementation STCaptureImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isFront = NO;
    
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f",_SportingMgr.sportingsportingTracking.distance];
    
    [self setupNotifications];
    
    [self setupSession];
}
- (AVCaptureDeviceInput *)createDeviceInput{
    
    //如何去获取两个不同的摄像头
    AVCaptureDevice  *device = nil;
    
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    for (AVCaptureDevice *dev in devices) {
        
        if(dev.position == AVCaptureDevicePositionBack && !self.isFront){
            
            device = dev;
            break;
        }else if(dev.position == AVCaptureDevicePositionFront && self.isFront){
            
            device = dev;
            break;
        }
    }
    
    if(devices == nil) return nil;
    
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
    return input;
}

- (void)setupSession {
    
    // 初始化输入设备时
    self.videoInput = [self createDeviceInput];
    
    // 初始化输出
    self.output = [AVCaptureStillImageOutput new];
    
    // 初始化 session
    self.session = [AVCaptureSession new];
    
    // 关联
    if(self.videoInput && [self.session canAddInput:self.videoInput]){
        
        [self.session addInput:self.videoInput];
    }
    
    if([self.session canAddOutput:self.output]){
        
        [self.session addOutput:self.output];
    }
    
    [self.previewView layoutIfNeeded];
    
    //预览
    AVCaptureVideoPreviewLayer  *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    
    layer.frame = self.previewView.bounds;
    
    [self.previewView.layer insertSublayer:layer atIndex:0];
    
    //设置预览模式
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    // 开启会话
    [self.session startRunning];
    
}

- (IBAction)actionClose:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  快门动画 -
- (void)openFlashView{
    [NSLayoutConstraint deactivateConstraints:@[self.leftFlashViewTrailingConstraint,self.rightFlashViewLeadingConstraint]];
    
    // 动画
    [UIView animateWithDuration:0.5 animations:^{
       
        [self.previewView layoutIfNeeded];
    } completion:^(BOOL finished) {
        
        [self takePicture];
    }];
}

- (void)closeFlashView {
    [NSLayoutConstraint activateConstraints:@[self.leftFlashViewTrailingConstraint,self.rightFlashViewLeadingConstraint]];
    
    // 动画
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.previewView layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        
    }];
}

- (IBAction)actionSwitchCamera:(id)sender {
    
    if(!self.session.isRunning){
        //分享图片
        return;
        
    }
    
    //关闭会话
    [self.session stopRunning];
    
    //移除输出
    [self.session removeInput:self.videoInput];
    
    self.isFront = !self.isFront;
    
    //重新创建输入
    self.videoInput = [self createDeviceInput];
    
    // 关联
    if(self.videoInput && [self.session canAddInput:self.videoInput]){
        
        [self.session addInput:self.videoInput];
    }
    
    // 重新启动
    [self.session startRunning];
}


#pragma mark - 按钮动画 -
- (void)rotateButtonAnimation{
    if(!self.session.isRunning){
        // 表示拍照已经完成
        [UIView transitionWithView:self.captureButton duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [self.captureButton setTitle:@"✔️" forState:UIControlStateNormal];
            
        } completion:^(BOOL finished) {
            
        }];
        
        [UIView transitionWithView:self.switchButton duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [self.switchButton setImage:[UIImage imageNamed:@"ic_waterprint_share"] forState:UIControlStateNormal];
            [self.switchButton setImage:[UIImage imageNamed:@"ic_waterprint_share_pressed"] forState:UIControlStateHighlighted];
        } completion:^(BOOL finished) {
            
        }];

    }else{
        //准备拍照
        [UIView transitionWithView:self.captureButton duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
            [self.captureButton setTitle:@"" forState:UIControlStateNormal];
            
        } completion:^(BOOL finished) {
            
        }];
        
        [UIView transitionWithView:self.switchButton duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [self.switchButton setImage:[UIImage imageNamed:@"ic_waterprint_revolve"] forState:UIControlStateNormal];
            [self.switchButton setImage:[UIImage imageNamed:@"ic_waterprint_revolve_pressed"] forState:UIControlStateHighlighted];
        } completion:^(BOOL finished) {
            
        }];

    }
    
    
}

#pragma mark - 拍照 -
- (void)takePicture{
    // 获取捕捉照片连接
    AVCaptureConnection  *conn = self.output.connections.firstObject;
    
    __weak typeof(self) weakself = self;
    
    //拍照
    [self.output captureStillImageAsynchronouslyFromConnection:conn completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        if(error != nil) return;
        
        // imageDataSampleBuffer 照片数据对象
        
        // 把照片数据对象转成jpeg 格式数据
        NSData  *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        UIImage *image = [UIImage imageWithData:imageData];
        
        // 计算被截取区域的高度
        CGFloat offset = ([UIScreen mainScreen].bounds.size.height - weakself.previewView.bounds.size.height) * 0.5;
        
        // 创建一个绘制上下文
        UIGraphicsBeginImageContextWithOptions(weakself.previewView.bounds.size, YES, 0);
        
        // 绘图
        [image drawInRect:CGRectInset(weakself.previewView.bounds, 0, - offset)];
        
        // 水印
        [weakself.waterprintImageView.image drawInRect:weakself.waterprintImageView.frame];
        [weakself.distanceLabel.attributedText drawInRect:weakself.distanceLabel.frame];
        
        //从上下文获取图片
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        //关闭上下文
        UIGraphicsEndImageContext();
        // 把图片装进相册中
        //completionTarget 完成回调目标 => 回调对象是谁
        
        UIImageWriteToSavedPhotosAlbum(newImage, weakself, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        
    }];

}
- (IBAction)actionTakePicture:(id)sender ;{
    
    if(!self.session.isRunning){
        [self.session startRunning];
        [self rotateButtonAnimation];
        return;
    }
    //打开快门
    [self openFlashView];
    
}

- (void)dealloc {
    [self.session stopRunning];
    [self teardownNotifications];
}

#pragma mark - 通知设置 -
- (void)setupNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sporingTrackingLineDidBeGeneratedNotification:) name:STSporingTrackingLineDidBeGeneratedNotification object:_SportingMgr];

}

- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 当线段被生成的时候引发通知
- (void)sporingTrackingLineDidBeGeneratedNotification:(NSNotification *)notification {
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f",_SportingMgr.sportingsportingTracking.distance];
}

#pragma mark - 相册保存成功回调 -
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    // 停止会话
    [self.session stopRunning];
    
    sleep(0.1);
    
    if(error == nil) {
        NSLog(@"保存成功");
    } else {
        NSLog(@"保存失败");
    }
    
    [self closeFlashView];
    [self rotateButtonAnimation];
}
@end
